"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
  ArrowLeft,
  Target,
  Users,
  Lightbulb,
  BarChart3,
  Award,
  Search,
  CheckCircle,
  AlertCircle,
  TrendingUp,
  Building,
  Globe,
  Sparkles,
  Brain,
  Zap,
  Shield,
  Star,
  Eye,
  Heart,
  MessageSquare,
  Download,
  Share2,
  BookOpen,
  Compass,
  Map,
  Flag,
  Rocket,
  Diamond,
  Crown,
  Gem
} from "lucide-react"

interface PositioningAnalysis {
  targetMarket: string
  valueProposition: string
  competitiveAdvantage: string
  brandPersonality: string
  messagingStrategy: string
  marketPosition: string
  differentiation: string[]
  recommendations: string[]
  score: number
}

export default function CompanyPositioningPage() {
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const [analysis, setAnalysis] = useState<PositioningAnalysis | null>(null)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  
  // 表单数据
  const [formData, setFormData] = useState({
    companyName: "",
    industry: "",
    businessModel: "",
    targetCustomers: "",
    productService: "",
    coreValues: "",
    uniqueFeatures: "",
    competitors: "",
    marketSize: "",
    businessGoals: "",
    challenges: "",
    budget: ""
  })

  const steps = [
    { id: 1, title: "基本信息", desc: "公司和业务基础信息" },
    { id: 2, title: "目标市场", desc: "客户群体和市场定位" },
    { id: 3, title: "产品特色", desc: "产品优势和差异化" },
    { id: 4, title: "竞争环境", desc: "竞品分析和市场环境" },
    { id: 5, title: "定位分析", desc: "生成定位策略报告" }
  ]

  const industries = [
    "科技/互联网", "电商/零售", "金融服务", "教育培训", 
    "医疗健康", "制造业", "餐饮服务", "文化娱乐",
    "房地产", "交通物流", "农业", "其他"
  ]

  const businessModels = [
    "B2B", "B2C", "B2B2C", "C2C", "SaaS", 
    "平台型", "订阅制", "服务型", "产品销售", "其他"
  ]

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const validateStep = (step: number): boolean => {
    switch (step) {
      case 1:
        return !!(formData.companyName && formData.industry && formData.businessModel)
      case 2:
        return !!(formData.targetCustomers && formData.marketSize)
      case 3:
        return !!(formData.productService && formData.uniqueFeatures && formData.coreValues)
      case 4:
        return !!(formData.competitors && formData.businessGoals)
      default:
        return true
    }
  }

  const nextStep = () => {
    if (validateStep(currentStep)) {
      setCurrentStep(prev => Math.min(5, prev + 1))
    }
  }

  const prevStep = () => {
    setCurrentStep(prev => Math.max(1, prev - 1))
  }

  const generateAnalysis = async () => {
    setLoading(true)
    
    try {
      // 模拟AI分析处理
      await new Promise(resolve => setTimeout(resolve, 3000))
      
      const mockAnalysis: PositioningAnalysis = {
        targetMarket: `${formData.targetCustomers}是您的核心目标市场，这个群体具有明确的${formData.productService}需求，市场容量约${formData.marketSize}。`,
        valueProposition: `基于您的${formData.uniqueFeatures}，我们建议将价值主张定位为"为${formData.targetCustomers}提供${formData.coreValues}的${formData.productService}解决方案"。`,
        competitiveAdvantage: `相比于${formData.competitors}，您的核心竞争优势体现在${formData.uniqueFeatures}，这将成为您在市场中的差异化定位基础。`,
        brandPersonality: `根据您的核心价值"${formData.coreValues}"，建议塑造专业、创新、可信赖的品牌人格，强调技术领先和客户成功。`,
        messagingStrategy: `主要传播策略应围绕"${formData.uniqueFeatures}"展开，突出解决客户痛点的能力，建立行业专家形象。`,
        marketPosition: `建议采用"挑战者"策略，在${formData.industry}领域中定位为创新引领者，专注服务${formData.targetCustomers}细分市场。`,
        differentiation: [
          `产品创新：${formData.uniqueFeatures}`,
          `服务模式：${formData.businessModel}优化`,
          `客户体验：专注${formData.targetCustomers}需求`,
          `技术优势：行业领先的解决方案`,
          `价值理念：坚持${formData.coreValues}`
        ],
        recommendations: [
          "建立清晰的品牌识别系统，统一视觉和语言风格",
          "专注核心目标客户群体，避免市场定位过于宽泛",
          "持续强化产品差异化特色，建立技术护城河",
          "建立客户成功案例库，增强品牌可信度",
          "制定阶段性市场推广策略，逐步扩大市场份额",
          "建立竞品监控机制，及时调整定位策略",
          "投资品牌建设，提升市场知名度和影响力"
        ],
        score: Math.floor(Math.random() * 20) + 80 // 80-100分
      }
      
      setAnalysis(mockAnalysis)
      setCurrentStep(5)
    } catch (error) {
      console.error("生成分析失败:", error)
    } finally {
      setLoading(false)
    }
  }

  const exportReport = () => {
    // 导出报告功能
    console.log("导出定位分析报告")
  }

  const shareReport = () => {
    // 分享报告功能
    console.log("分享定位分析报告")
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 头部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-4xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => router.push("/")}
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="w-4 h-4" />
                <span>返回首页</span>
              </Button>
              <div className="h-6 w-px bg-slate-200" />
              <div className="flex items-center space-x-2">
                <Target className="w-6 h-6 text-cyan-600" />
                <h1 className="text-xl font-bold text-slate-900">公司定位分析</h1>
              </div>
            </div>
            
            <div className="flex items-center space-x-2">
              <span className="text-sm text-slate-600">
                步骤 {currentStep}/5
              </span>
              <Progress value={(currentStep / 5) * 100} className="w-20" />
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto px-6 py-8">
        {/* 步骤指示器 */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            {steps.map((step) => (
              <div
                key={step.id}
                className={`flex flex-col items-center space-y-2 ${
                  step.id <= currentStep ? "text-cyan-600" : "text-slate-400"
                }`}
              >
                <div
                  className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium ${
                    step.id < currentStep
                      ? "bg-cyan-600 text-white"
                      : step.id === currentStep
                      ? "bg-cyan-100 text-cyan-600 border-2 border-cyan-600"
                      : "bg-slate-100 text-slate-400"
                  }`}
                >
                  {step.id < currentStep ? (
                    <CheckCircle className="w-5 h-5" />
                  ) : (
                    step.id
                  )}
                </div>
                <div className="text-center">
                  <div className="text-sm font-medium">{step.title}</div>
                  <div className="text-xs text-slate-500">{step.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 表单内容 */}
        <Card className="bg-white/70 backdrop-blur-sm border-0 shadow-lg">
          <CardContent className="p-8">
            {currentStep === 1 && (
              <div className="space-y-6">
                <div className="text-center mb-8">
                  <Building className="w-12 h-12 text-cyan-600 mx-auto mb-4" />
                  <h2 className="text-2xl font-bold text-slate-900 mb-2">基本信息</h2>
                  <p className="text-slate-600">请填写您公司的基础信息，帮助我们了解您的业务背景</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      公司名称 *
                    </label>
                    <Input
                      placeholder="请输入公司名称"
                      value={formData.companyName}
                      onChange={(e) => handleInputChange("companyName", e.target.value)}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      所属行业 *
                    </label>
                    <select
                      className="w-full px-3 py-2 border border-slate-200 rounded-lg bg-white"
                      value={formData.industry}
                      onChange={(e) => handleInputChange("industry", e.target.value)}
                    >
                      <option value="">请选择行业</option>
                      {industries.map(industry => (
                        <option key={industry} value={industry}>{industry}</option>
                      ))}
                    </select>
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      商业模式 *
                    </label>
                    <select
                      className="w-full px-3 py-2 border border-slate-200 rounded-lg bg-white"
                      value={formData.businessModel}
                      onChange={(e) => handleInputChange("businessModel", e.target.value)}
                    >
                      <option value="">请选择商业模式</option>
                      {businessModels.map(model => (
                        <option key={model} value={model}>{model}</option>
                      ))}
                    </select>
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      预算范围
                    </label>
                    <Input
                      placeholder="如：50万-100万"
                      value={formData.budget}
                      onChange={(e) => handleInputChange("budget", e.target.value)}
                    />
                  </div>
                </div>
              </div>
            )}

            {currentStep === 2 && (
              <div className="space-y-6">
                <div className="text-center mb-8">
                  <Users className="w-12 h-12 text-cyan-600 mx-auto mb-4" />
                  <h2 className="text-2xl font-bold text-slate-900 mb-2">目标市场</h2>
                  <p className="text-slate-600">定义您的目标客户群体和市场规模</p>
                </div>

                <div className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      目标客户群体 *
                    </label>
                    <Textarea
                      placeholder="请详细描述您的目标客户，如：25-40岁的企业中层管理者，注重效率和品质..."
                      value={formData.targetCustomers}
                      onChange={(e) => handleInputChange("targetCustomers", e.target.value)}
                      rows={4}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      市场规模估算 *
                    </label>
                    <Input
                      placeholder="如：中国一二线城市约500万目标用户"
                      value={formData.marketSize}
                      onChange={(e) => handleInputChange("marketSize", e.target.value)}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      主要挑战
                    </label>
                    <Textarea
                      placeholder="描述您在市场拓展中面临的主要挑战..."
                      value={formData.challenges}
                      onChange={(e) => handleInputChange("challenges", e.target.value)}
                      rows={3}
                    />
                  </div>
                </div>
              </div>
            )}

            {currentStep === 3 && (
              <div className="space-y-6">
                <div className="text-center mb-8">
                  <Lightbulb className="w-12 h-12 text-cyan-600 mx-auto mb-4" />
                  <h2 className="text-2xl font-bold text-slate-900 mb-2">产品特色</h2>
                  <p className="text-slate-600">描述您的产品或服务的独特价值</p>
                </div>

                <div className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      产品/服务描述 *
                    </label>
                    <Textarea
                      placeholder="详细描述您的产品或服务..."
                      value={formData.productService}
                      onChange={(e) => handleInputChange("productService", e.target.value)}
                      rows={4}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      独特功能/特色 *
                    </label>
                    <Textarea
                      placeholder="列出您产品的独特功能或特色，与竞品的差异化优势..."
                      value={formData.uniqueFeatures}
                      onChange={(e) => handleInputChange("uniqueFeatures", e.target.value)}
                      rows={4}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      核心价值理念 *
                    </label>
                    <Input
                      placeholder="如：让科技更简单、为客户创造价值..."
                      value={formData.coreValues}
                      onChange={(e) => handleInputChange("coreValues", e.target.value)}
                    />
                  </div>
                </div>
              </div>
            )}

            {currentStep === 4 && (
              <div className="space-y-6">
                <div className="text-center mb-8">
                  <BarChart3 className="w-12 h-12 text-cyan-600 mx-auto mb-4" />
                  <h2 className="text-2xl font-bold text-slate-900 mb-2">竞争环境</h2>
                  <p className="text-slate-600">分析竞争对手和市场环境</p>
                </div>

                <div className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      主要竞争对手 *
                    </label>
                    <Textarea
                      placeholder="列出3-5个主要竞争对手，并简述他们的优劣势..."
                      value={formData.competitors}
                      onChange={(e) => handleInputChange("competitors", e.target.value)}
                      rows={4}
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      业务目标 *
                    </label>
                    <Textarea
                      placeholder="描述您的短期和长期业务目标..."
                      value={formData.businessGoals}
                      onChange={(e) => handleInputChange("businessGoals", e.target.value)}
                      rows={3}
                    />
                  </div>
                </div>

                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    我们将基于您提供的信息，运用AI算法分析您的市场定位策略，生成专业的定位分析报告。
                  </AlertDescription>
                </Alert>
              </div>
            )}

            {currentStep === 5 && analysis && (
              <div className="space-y-8">
                <div className="text-center mb-8">
                  <div className="w-16 h-16 bg-gradient-to-br from-cyan-500 to-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Award className="w-8 h-8 text-white" />
                  </div>
                  <h2 className="text-2xl font-bold text-slate-900 mb-2">定位分析报告</h2>
                  <p className="text-slate-600">基于AI算法生成的专业公司定位策略分析</p>
                  
                  <div className="flex items-center justify-center space-x-4 mt-4">
                    <div className="flex items-center space-x-2">
                      <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                      <span className="text-sm text-slate-600">定位评分: {analysis.score}分</span>
                    </div>
                    <Badge className="bg-green-100 text-green-700">
                      {analysis.score >= 90 ? "优秀" : analysis.score >= 80 ? "良好" : "需优化"}
                    </Badge>
                  </div>
                </div>

                <Tabs defaultValue="positioning" className="w-full">
                  <TabsList className="grid w-full grid-cols-4">
                    <TabsTrigger value="positioning">市场定位</TabsTrigger>
                    <TabsTrigger value="differentiation">差异化</TabsTrigger>
                    <TabsTrigger value="strategy">策略建议</TabsTrigger>
                    <TabsTrigger value="action">行动计划</TabsTrigger>
                  </TabsList>
                  
                  <TabsContent value="positioning" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Target className="w-5 h-5" />
                          <span>目标市场分析</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.targetMarket}</p>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Diamond className="w-5 h-5" />
                          <span>价值主张</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.valueProposition}</p>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Shield className="w-5 h-5" />
                          <span>竞争优势</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.competitiveAdvantage}</p>
                      </CardContent>
                    </Card>
                  </TabsContent>
                  
                  <TabsContent value="differentiation" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Sparkles className="w-5 h-5" />
                          <span>差异化要素</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-3">
                          {analysis.differentiation.map((item, index) => (
                            <div key={index} className="flex items-start space-x-3">
                              <div className="w-2 h-2 bg-cyan-500 rounded-full mt-2 flex-shrink-0"></div>
                              <p className="text-slate-700">{item}</p>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Crown className="w-5 h-5" />
                          <span>品牌人格</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.brandPersonality}</p>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <MessageSquare className="w-5 h-5" />
                          <span>传播策略</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.messagingStrategy}</p>
                      </CardContent>
                    </Card>
                  </TabsContent>
                  
                  <TabsContent value="strategy" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Compass className="w-5 h-5" />
                          <span>市场定位策略</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-slate-700 leading-relaxed">{analysis.marketPosition}</p>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Lightbulb className="w-5 h-5" />
                          <span>策略建议</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-4">
                          {analysis.recommendations.map((rec, index) => (
                            <div key={index} className="flex items-start space-x-3 p-3 bg-slate-50 rounded-lg">
                              <div className="w-6 h-6 bg-cyan-100 text-cyan-600 rounded-full flex items-center justify-center text-sm font-medium flex-shrink-0">
                                {index + 1}
                              </div>
                              <p className="text-slate-700">{rec}</p>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                  
                  <TabsContent value="action" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center space-x-2">
                          <Rocket className="w-5 h-5" />
                          <span>实施计划</span>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-4">
                          <div className="p-4 border-l-4 border-cyan-500 bg-cyan-50">
                            <h4 className="font-medium text-slate-900 mb-2">第一阶段：基础建设（1-3个月）</h4>
                            <ul className="text-sm text-slate-700 space-y-1">
                              <li>• 完善品牌视觉识别系统</li>
                              <li>• 制定统一的品牌传播语言</li>
                              <li>• 建立核心产品差异化特色</li>
                            </ul>
                          </div>
                          
                          <div className="p-4 border-l-4 border-blue-500 bg-blue-50">
                            <h4 className="font-medium text-slate-900 mb-2">第二阶段：市场验证（3-6个月）</h4>
                            <ul className="text-sm text-slate-700 space-y-1">
                              <li>• 在目标客户群体中测试定位策略</li>
                              <li>• 收集客户反馈并优化定位</li>
                              <li>• 建立客户成功案例库</li>
                            </ul>
                          </div>
                          
                          <div className="p-4 border-l-4 border-purple-500 bg-purple-50">
                            <h4 className="font-medium text-slate-900 mb-2">第三阶段：规模化推广（6个月+）</h4>
                            <ul className="text-sm text-slate-700 space-y-1">
                              <li>• 全面实施市场推广策略</li>
                              <li>• 扩大品牌影响力和市场份额</li>
                              <li>• 持续监控和优化定位策略</li>
                            </ul>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                </Tabs>

                <div className="flex justify-center space-x-4 pt-6 border-t">
                  <Button onClick={exportReport} className="flex items-center space-x-2">
                    <Download className="w-4 h-4" />
                    <span>导出报告</span>
                  </Button>
                  <Button variant="outline" onClick={shareReport} className="flex items-center space-x-2">
                    <Share2 className="w-4 h-4" />
                    <span>分享报告</span>
                  </Button>
                </div>
              </div>
            )}

            {/* 操作按钮 */}
            {currentStep < 5 && (
              <div className="flex justify-between pt-8 border-t">
                <Button
                  variant="outline"
                  onClick={prevStep}
                  disabled={currentStep === 1}
                  className="flex items-center space-x-2"
                >
                  <span>上一步</span>
                </Button>
                
                {currentStep === 4 ? (
                  <Button
                    onClick={generateAnalysis}
                    disabled={!validateStep(currentStep) || loading}
                    className="flex items-center space-x-2 bg-gradient-to-r from-cyan-600 to-blue-600 hover:from-cyan-700 hover:to-blue-700"
                  >
                    {loading ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        <span>AI分析中...</span>
                      </>
                    ) : (
                      <>
                        <Brain className="w-4 h-4" />
                        <span>生成定位分析</span>
                      </>
                    )}
                  </Button>
                ) : (
                  <Button
                    onClick={nextStep}
                    disabled={!validateStep(currentStep)}
                    className="flex items-center space-x-2"
                  >
                    <span>下一步</span>
                  </Button>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  )
}